package com.blog.controller;

import com.blog.annotation.RequiredTime;
import com.blog.entity.User;
import com.blog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 定义用户数据请求处理的Controller对象
 */
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;


    /**
     * @RequiredTime 注解描述的方法为一个时间切入点方法，也称之为目标方法
     * @param user
     * @param session
     * @return
     */
    @RequiredTime
    @PostMapping("/user/login")
    public int login(@RequestBody User user, HttpSession session){

        System.out.println(user);
        User loginUser = userMapper.selectByUserName(user.getUsername());
        if(loginUser==null)
            //throw new RuntimeException("user is not exits");
            return 2;//2表示用户不存在
        if(loginUser.getPassword().equals(
                DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))){
            session.setAttribute("user", user);
            return 1;//表示密码正确
        }
        return 3;//表示密码不正确
    }
    @GetMapping("/user/currentUser")
    public User currentUser(HttpSession session){
        return (User)session.getAttribute("user");
    }

    @RequiredTime
    @GetMapping("/user/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
